package com.cloud.wms.base;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.appcompat.app.AlertDialog;

import com.cloud.wms.R;
import com.cloud.core.base.BasePresenter;
import com.cloud.core.base.BaseView;
import com.cloud.core.config.ScanConfig;
import com.cloud.core.eventBus.EventBusUtil;
import com.cloud.core.tools.PlayVoiceManager;
import com.cloud.core.tools.VolumeManager;
import com.cloud.core.widget.dialog.LoadingDialog;
import com.cloud.widget.ScanText;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.injection.components.ActivityComponent;
import com.cloud.wms.injection.components.DaggerActivityComponent;
import com.cloud.wms.injection.modules.ActivityModule;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.dylanc.loadinghelper.LoadingHelper;
import com.gyf.immersionbar.ImmersionBar;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.trello.rxlifecycle3.LifecycleTransformer;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import es.dmoral.toasty.Toasty;
import io.reactivex.disposables.CompositeDisposable;

/**
 * @Author:Chen
 * @Date: 2021-01-14 10:52
 * @Description:
 */
public abstract class BaseActivity<P extends BasePresenter> extends RxAppCompatActivity implements BaseView, LoadingHelper.OnReloadListener {
    @Inject
    protected P mPresenter;

    protected Activity mContext;

    private Unbinder mUnbinder;

    private LoadingDialog mDialog;

    protected CompositeDisposable disposable = new CompositeDisposable();

    protected View.OnKeyListener onKeyListenerImp = (v, keyCode, event) -> {
        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
            EditText editText = (EditText) v;
            String result = editText.getText().toString().trim();
            if (!TextUtils.isEmpty(result)) {
                onScanHandle(result, ScanConfig.SCAN_INFRARED_RESULT_CODE);
            }
        }
        return keyCode == KeyEvent.KEYCODE_ENTER;
    };
    protected LoadingHelper loadingHelper;
    private ScanText scanText;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getResId() != 0) {
            setContentView(getResId());
        }
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        setupComponent();
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
        initBar();
        initToolBar();
        initEvent();
        if (isUseEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBusUtil.register(this);
        }
    }

    /**
     * 初始化状态栏
     */
    protected void initBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.bg_bar)
                .autoDarkModeEnable(true)//自动状态栏字体和导航栏图标变色，必须指定状态栏颜色和导航栏颜色才可以自动变色哦
                .init();
    }

    protected void initToolBar() {
    }

    @Override
    public void onReload() {

    }

    @Override
    public void onAlert(String content, DialogInterface.OnClickListener listener) {
        AlertDialog alertDialog = new AlertDialogBuilder(this)
                .setTitle("提示")
                .setMessage(content)
                .setPositiveButton("确定", listener)
                .setNegativeButton("取消", null)
                .show();
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).clearFocus();
    }

    @Override
    public void error(String msg) {
        Toasty.info(this, msg).show();
    }

    @Override
    public void info(String msg) {
        Toasty.info(this, msg).show();
    }

    @Override
    public void success(String msg) {
        Toasty.success(this, msg).show();
    }

    protected LoadingDialog getDialog() {
        if (mDialog == null) {
            mDialog = new LoadingDialog.Builder(mContext).create();
        }
        return mDialog;
    }

    protected void dismiss() {
        if (mDialog == null) {
            return;
        }
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    protected boolean isUseEventBus() {
        return false;
    }

    protected abstract int getResId();

    protected abstract void initEvent();

    protected abstract void setupComponent();

    protected void initScanText(ScanText scanText) {
        if (scanText != null) {
            this.scanText = scanText;
            scanText.getFocus();
            HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE, HmsScan.CODE128_SCAN_TYPE).create();
            scanText.setOnScanListener(() -> ScanUtil.startScan(BaseActivity.this, ScanConfig.SCAN_CAMERA_REQUEST_CODE, options));
            scanText.setOnKeyListener(onKeyListenerImp);
        }
    }

    @Override
    public void showLoading() {
        getDialog().show();
    }

    @Override
    public void hideLoading() {
        dismiss();
    }

    @Override
    public void showError() {
        if (loadingHelper != null) {
            loadingHelper.showErrorView();
        }
    }

    @Override
    public void showContent() {
        if (loadingHelper != null) {
            loadingHelper.showContentView();
        }
    }

    @Override
    public void showEmpty() {
        if (loadingHelper != null) {
            loadingHelper.showEmptyView();
        }
    }

    @CallSuper
    protected void onScanHandle(String result, int resultCode) {
    }

    public void shockAlert() {
        Vibrator vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(1000);
    }

    /**
     * 成功
     */
    public void successVoice() {
        new VolumeManager(this).setVoice(100);
        PlayVoiceManager.with(this).play(R.raw.voice_success);
    }

    /**
     * 错误
     */
    public void errorVoice() {
        new VolumeManager(this).setVoice(100);
        PlayVoiceManager.with(this).play(R.raw.voice_error);
    }

    /**
     * 扫描错误
     */
    public void scanErrorVoice() {
        new VolumeManager(this).setVoice(100);
        PlayVoiceManager.with(this).play(R.raw.scan_error);
    }

    /**
     * 重复扫描
     */
    public void scanRepeatVoice() {
        new VolumeManager(this).setVoice(100);
        PlayVoiceManager.with(this).play(R.raw.scan_repeat);
    }

    public void scanVoice(@RawRes int voice) {
        new VolumeManager(this).setVoice(100);
        PlayVoiceManager.with(this).play(voice);
    }

    public void scanVoice(@RawRes Integer[] voice) {
        new VolumeManager(this).setVoice(100);
        for (int i = 0; i < voice.length; i++) {
            PlayVoiceManager.with(this).play(voice[i]);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (disposable != null) {
            disposable.dispose();
        }
        mUnbinder.unbind();
        if (isUseEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBusUtil.unregister(this);
        }
        dismiss();
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    @Override
    public Context provideContext() {
        return mContext;
    }

    protected ActivityComponent getActivityComponent() {
        return DaggerActivityComponent.builder()
                .applicationComponent(FineExApplication.component())
                .activityModule(new ActivityModule(this))
                .build();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ScanConfig.SCAN_CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            /**
             * 扫码返回的数据（码格式，扫码类型，扫码内容）
             * obj.getOriginalValue();//扫码的结果
             * obj.getScanType();//二维码的格式
             * obj.getScanTypeForm();//二维码内容的类型
             */
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null && !TextUtils.isEmpty(obj.getOriginalValue())) {
                if (scanText != null) {
                    scanText.setText(obj.getOriginalValue().trim());
                }
                onScanHandle(obj.getOriginalValue().trim(), ScanConfig.SCAN_INFRARED_RESULT_CODE);
            } else {
                info("扫描结果解析失败！");
            }
        }
    }
}
